package concurrent.chapter6;

import java.util.Random;

public class WriterWorker extends Thread {
    private static final Random randmon = new Random(System.currentTimeMillis());
    private final SharedData data;
    private final String filler;
    private int index = 0;

    public WriterWorker(SharedData data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        //try不要放在while循环里，否则产生异常后还会再循环操作
        try {
            while (true) {
                char c = nextChar();
                data.write(c);
                Thread.sleep(randmon.nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private char nextChar() {
        char c = filler.charAt(index);
        index++;
        if (index >= filler.length()) {
            index = 0;
        }
        return c;
    }
}
